package com.ruoyi.iot.influxdb.repository.metric;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.iot.config.Constants;
import com.ruoyi.iot.influxdb.config.dbquery.BuildResultService;
import org.influxdb.InfluxDB;
import org.influxdb.dto.Point;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

@Component("InfluxdbMetricsRepository")
public class InfluxdbMetricsRepository<T> implements MetricsRepository<T> {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private BuildResultService<T> buildService;

    @Autowired
    private InfluxDB influxDB;
    @Resource
    private RedisCache redisUtil;

    /**
     * 从缓存中查询最新的指标数据
     * @param key
     * @return 指标数据
     */
    public T findByDeviceIdFromCache(String key ) {
        Object obj = redisUtil.getCacheObject( key );
        if ( null == obj ){
            return null;
        }
        return (T)obj;
    }

    /**
     * 保存记录
     * 保存到  redis 和 influxdb
     * @param deviceId
     * @param metrics
     * @param persistentData
     */
    public void save( String deviceId, T metrics, boolean persistentData ) {
        // redis
        redisUtil.setCacheObject( deviceId, metrics  );
        if ( persistentData ){
            Point point = Point.measurementByPOJO(metrics.getClass()).addFieldsFromPOJO(metrics).build();
            influxDB.setDatabase(Constants.INFLUXDB_DATABASE_PLAT);
            // influxDB.setLogLevel(InfluxDB.LogLevel.BASIC);
            influxDB.write( point);
        }
    }







}
